﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using ProtoBuf.Message;
#if !NAKED
using supersdkUnity;
#endif
namespace Login
{
    public enum LoginState
    {
        CG,
        LoginEnter,             // 登陆URL
        CheckVersion,           // 校验版本
        Activation,             // 输入激活码
        SyncDataAndRes,         // 更新数据
        Notice,                 // 公告
        LoginAuth,              // 账户密码校验
        GetServerList,          // 获取服务器列表
        LoginOver,
        UserLogin,
        GenerateName,
        PlayerCreate,
        PlayerLogin,

    }
    public enum ServerListType
    {
        My = 0,
        All = 1
    }


    public class LoginManager : Fsm.FsmControllerBaseMono<LoginState>
    {
        public LoginUI loginUI;

        public GameObject bgPanel;

        public GameObject serverPanel;

        public GameObject nickName;

        /// <summary>
        /// 用户状态（新用户还是老用户）
        /// </summary>
        public bool isFirstCreate = false;
        public bool isAuthPassed = false;
        public static bool isNetFlag = false;
        public string nickNameStr = "";
        public ServerListType serverType = ServerListType.All;

        //将要登录场景
        public static string willLoginScene;

        public string ZoneIp
        {
            get
            {
                return GetServerIP(StaticData.playerData.serverUID);
            }
        }
        public int ZoneId
        {
            get
            {
                return GetServerID(StaticData.playerData.serverUID);
            }
        }
        public string Display
        {
            get
            {
                return GetDisplay(StaticData.playerData.serverUID);
            }
        }
        public string ZoneName
        {
            get
            {
                return GetServerName(StaticData.playerData.serverUID);
            }
        }



        /// <summary>
        /// 清除ZoneID,UserName,PassWord的缓存
        /// </summary>
        public void CleanCache()
        {
            StaticData.playerData.ClearSelectServerCache();
            StaticData.UserName = "";
            StaticData.PassWord = "";
            nickNameStr = "";
            isAuthPassed = false;

        }
        void Update()
        {
            UpdateState();
           

        }

        public string authCode;     // 登陆时校验用字段

        public void Start()
        {

            gameObject.SetActive(true);

            InitState();

            loginUI.GetComponent<LoginUI>().Init();

        }
        public override void InitState()
        {
           
            Debug.Log("BUGLY exception");
            allStates = new Dictionary<LoginState, Fsm.FsmStateMonoBase<LoginState>>();
            allStates[LoginState.LoginEnter] = new LoginEnter(LoginState.LoginEnter, this);
            allStates[LoginState.CheckVersion] = new LoginCheckVersion(LoginState.CheckVersion, this);
            allStates[LoginState.Activation] = new LoginActivation(LoginState.Activation, this);
            allStates[LoginState.SyncDataAndRes] = new LoginAsyncDataAndRes(LoginState.SyncDataAndRes, this);
            allStates[LoginState.Notice] = new LoginNotice(LoginState.Notice, this);
            allStates[LoginState.LoginAuth] = new LoginAuth(LoginState.LoginAuth, this);
            allStates[LoginState.GetServerList] = new LoginGetServerList(LoginState.GetServerList, this);
            allStates[LoginState.UserLogin] = new LoginUserLogin(LoginState.UserLogin, this);
            allStates[LoginState.GenerateName] = new LoginGenerateName(LoginState.GenerateName, this);
            allStates[LoginState.PlayerCreate] = new LoginPlayerCreate(LoginState.PlayerCreate, this);
            allStates[LoginState.PlayerLogin] = new LoginPlayerLogin(LoginState.PlayerLogin, this);


            SwitchState(LoginState.LoginEnter);
        }

        public void AskGetServerList(System.Action onGetServerList)
        {
            CSGetServerList msg = new CSGetServerList();
            msg.platformUid = StaticData.UserName;
            msg.channelId = GameConfig.Instance.GetChannelId;
            msg.channelName = GameConfig.Instance.GetChannelName;
            msg.appVersion = GameConfig.Instance.AppVersion;
            msg.deviceDesc = SystemInfo.deviceModel;//设备型号
            msg.deviceId = GameConfig.Instance.GetDeviceID;//唯一的设备标示
            msg.resVersoin = GameConfig.Instance.ResVersion;


            NetAPI.SendHttp(OpDefine.CSGetServerList, msg, (pack, b) =>
            {
                if (b)
                {
                    SCGetServerList _msg = pack.kBody as SCGetServerList;
                    InitServerInfo(_msg);
                    loginUI.ShowServerPanel();
                    if (onGetServerList != null)
                    {
                        onGetServerList();
                    }
                }
            });
        }

        public void LoginDone()
        {
            Destroy(gameObject);
            LoadingPanel.Instance.ShowLoading();
            CameraTool.Instance.sceneCamera.enabled = true;
            LoginScene();
        }

        void LoginScene()
        {
            if (LoginManager.willLoginScene.StartsWith(ServerScene.Town))
            {
                ManagerController.Instance.LoginToUI();
            }
            else if (LoginManager.willLoginScene.StartsWith(ServerScene.Union))
            {
                ManagerController.Instance.LoginToUnion();
            }
            else if (LoginManager.willLoginScene.StartsWith(ServerScene.Field))
            {
                UI.UIFieldRunMap.fieldId = "";
                ManagerController.Instance.LoginToField(LoginManager.willLoginScene);
            }
            else if (LoginManager.willLoginScene.StartsWith(ServerScene.UnionFight))
            {
                ManagerController.Instance.LoginToUnionFight();
            }
            else
            {
                Debug.LogError("[ERROR] login error vill load scene:" + LoginManager.willLoginScene);
            }

        }


        public string GetServerUrlFromIpStr(string ip)
        {
            return @"http://" + ip + @"/sao/";
        }

        public string GetCurrentServerUrl()
        {
            if (!string.IsNullOrEmpty(ZoneIp))
            {
                return GetServerUrlFromIpStr(this.ZoneIp);
            }
            else
            {
                return "";
            }
        }

        public bool IsCurrentServerMaintain()
        {
            foreach (var zone in allServerInfo)
            {
                if (zone.globalServerKey == StaticData.playerData.serverUID)
                {
                    if (zone.state == ServerState.maintain)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        public List<ProtoBuf.Message.ConfigServerZone> allServerInfo;
        public List<ProtoBuf.Message.ConfigPlayerServer> myServerInfo;

        public void InitServerInfo(ProtoBuf.Message.SCGetServerList msg)
        {
            this.allServerInfo = msg.serverList;
            this.myServerInfo = msg.playerServerList;
            if (!string.IsNullOrEmpty(StaticData.playerData.serverUID))
            {
                bool isCacheServerValid = false;
                foreach (var server in allServerInfo)
                {
                    if (server.globalServerKey == StaticData.playerData.serverUID)
                    {
                        isCacheServerValid = true;
                        StaticData.playerData.currentZone = server;
                        break;
                    }
                }
                if (!isCacheServerValid)
                {
                    var NewestServer = GetNewestServerInfo();
                    if (NewestServer != null)
                    {
                        StaticData.playerData.SelectServer(NewestServer);
                    }
                    else
                    {
                        StaticData.playerData.ClearSelectServerCache();
                    }
                }
            }
            else
            {
                var NewestServer = GetNewestServerInfo();
                if (NewestServer != null)
                {
                    StaticData.playerData.SelectServer(NewestServer);
                }
                else
                {
                    StaticData.playerData.ClearSelectServerCache();
                }
            }
        }

        public ConfigServerZone GetNewestServerInfo()
        {
            List<ConfigServerZone> recommandServers = new List<ConfigServerZone>();
            foreach (var server in allServerInfo)
            {
                if (server.state == ServerState.recommend)
                {
                    recommandServers.Add(server);
                }
            }
            if (recommandServers.Count > 0)
            {
                return recommandServers[recommandServers.Count - 1];
            }
            else
            {
                if (allServerInfo.Count > 0)
                {
                    return allServerInfo[allServerInfo.Count - 1];
                }
            }
            return null;
        }

        public ConfigPlayerServer GetPlayerServerInfo(string serverKey)
        {
            ConfigPlayerServer server = null;
            foreach (var info in myServerInfo)
            {
                if (info.globalServerKey == serverKey)
                {
                    server = info;
                    break;
                }
            }
            if (server != null && GetServerInfo(server.globalServerKey) != null)
            {
                return server;
            }
            return null;
        }

        public ConfigServerZone GetServerInfo(string serverKey)
        {
            foreach (var info in allServerInfo)
            {
                if (info.globalServerKey == serverKey)
                    return info;
            }
            return null;
        }
        public string GetDisplay(string serverKey)
        {
            foreach (var info in allServerInfo)
            {
                if (info.globalServerKey == serverKey)
                    return info.display;
            }
            return "";
        }
        public string GetServerName(string serverKey)
        {
            foreach (var info in allServerInfo)
            {
                if (info.globalServerKey == serverKey)
                    return info.name;
            }
            return "";
        }
        public int GetServerID(string serverKey)
        {
            foreach (var info in allServerInfo)
            {
                if (info.globalServerKey == serverKey)
                    return info.serverId;
            }
            return -1;
        }
        public string GetServerIP(string serverKey)
        {
            foreach (var info in allServerInfo)
            {
                if (info.globalServerKey == serverKey)
                    return info.serverIp;
            }
            return "";
        }

        public void LoginAuthPass()
        {
            Debug.Log(" loginManager LoginAuthPass");
            Debug.Log("[DEBUG] LoginManager time = " + ServerTimerTool.ClientJavaTime());
            var state = GetState(LoginState.LoginAuth) as LoginAuth;
            state.LoginAuthPass();
        }

        public void ShowCgMovie()
        {
#if (UNITY_ANDROID || UNITY_IPHONE) && !UNITY_EDITOR
                Handheld.PlayFullScreenMovie("video.mp4",Color.black,
                    FullScreenMovieControlMode.CancelOnInput,FullScreenMovieScalingMode.AspectFit);
#endif
        }

        public void ShowFirstBattle()
        {
            ManagerController.Instance.LoginToBattle();
            Destroy(gameObject);
        }

    }

    public class ServerState
    {
        public const string normal = "normal";
        public const string recommend = "recommend";
        public const string maintain = "maintain";
        public const string busy = "busy";
    }

}